#include "connection.h"

int socketfd = 0;

int connectionToServer()
{
	struct sockaddr_in addr;

	struct hostent* ptr_hostinfo = gethostbyname(QQ_SMTP_SERVER);

	if(ptr_hostinfo==NULL)
	{
		perror(" ***** Cannot get the QQ Mail Server IP ***** \n");
		exit(1);
	}

	char** ptr_addrs = ptr_hostinfo->h_addr_list;

	char IP[20];
	memset(&IP, 0, sizeof(IP));
	
	while(*ptr_addrs!=NULL)
	{
		printf("QQ Mail Server IP is : %s \n", inet_ntoa(*(struct in_addr *)*ptr_addrs));
		strcpy(IP, inet_ntoa(*(struct in_addr *)*ptr_addrs));
		++ptr_addrs;
	}
	
	memset(&addr, 0, sizeof(addr));

	socketfd = socket(AF_INET, SOCK_STREAM, 0);

	addr.sin_family = AF_INET;
	addr.sin_addr.s_addr = inet_addr(IP);
	addr.sin_port = htons(QQ_SMTP_PROT);

	int res = connect(socketfd, (struct sockaddr *)&addr, sizeof(addr));
	
	if(res == -1)
	{
		perror(" Cannot connect to QQ Mail Server ! ");
		releaseSocket(socketfd);
		exit(1);
	}

	char buffer[80];
	int readNum = read(socketfd, buffer, sizeof(buffer));

	buffer[readNum]='\0';

	printf("  %s  \n", buffer);	

	return socketfd;
}



void releaseSocket()
{
	close(socketfd);
}

int sendCommandAndGetRsp(const char* command, char* buf)
{
	int count = write(socketfd, command, strlen(command));
	//printf("write count:%d\n", count);
	//printf("write command:%s\n", command);
	if(count==-1)
	{
		perror("Error\n");
		exit(1);
	}

	int res = read(socketfd, buf, 50);	
	if(res==0)
		return 0;	
	printf("*** Server Answers : %s \n", buf);
	char* p = strtok(buf, " ");
	int returnCode = atoi(p);
	
	return returnCode;
}
